//****   博客后台文章管理    ********//

var blogArticle = function(){
    var blogArticle = this;

    this.URL = {
        list:"/blogArticle/list/"+$("#contentType").val(),
        addArticle: "/blogArticle/add",
        updateArticle: "/blogArticle/update",
        deleteArticle:"/blogArticle/delete",
        listCategoryTree: "/blogCategory/listCategoryTree",
        searchContent:"/blogArticle/search"
    }
    this.inputValue;
    this.isAddOrUpdate = 0;        //0默认新增
    this.tableObj =  $("#listArticleTable");
    this.ajaxCache = {};//定义缓存对象
    this.dataGridInit = function (){
        $("#listArticleTable").datagrid({
            url:blogArticle.URL.list,
            method:'POST',
            checkOnSelect:true,
            singleSelect:true,
            collapsible: true,
            pagination: true,
            remoteSort: false,
            toolbar: '#tb',
            rownumbers: true,
            fit: true,
            pageSize: 20,
            pageList: [20, 30, 50, 80, 100, 200],
            onDblClickRow: function (index,row){
                $("#blogContentDialog").dialog("setTitle",$("#contentTypeZh").val()+"内容")
                $("#blogContentDialog").dialog("open");
                $("#contentInfo").html(row.content);
            },
            columns:[[
                {field:'id',checkbox:true},
                {field:'categoryId',hidden:true },
                {field:'category',title:'类别',width:200,align: 'left' },
                {field:'title',title:'标题',width:200,align: 'left'},
                {field:'content',title:'内容',width:350,formatter:function(val,row){
                    return "<div style='height: 35px;'>"+getCont(val)+"</div>"
                },align: 'left'},
                {field:'label',title:'标签',width:200 ,align: 'left'},
                {field:'createTime',title:'创建时间',width:200 ,formatter:function(val,row){
                    return val.replace(/\.0/g,"")
                },align: 'left'},
                {field:'createName',title:'创建人',width:100,align: 'left' },
                {field:'recommend',title:'推荐',width:100,formatter:function(val,row){
                    if(val == '0')return '否';else return '是';
                },align: 'left'},
                {field:'readQuantity',title:'阅读量',width:100,align: 'left'}
            ]]
        })
    }

    ///按钮初始化  #(新增    修改    删除    搜索   )
    this.buttonInit = function(){

        $("#saveContent").hide();//列表界面保存按钮不显示

        //*******新增
            $("#newContent").click(function (){
                blogArticle.isAddOrUpdate = 0;
                var title = "新建"+$("#contentTypeZh").val();

                if ($("#datetabs").tabs('exists', title)){
                    $("#datetabs").tabs('select', title);
                } else {
                    var content =
                        '<form id="addArticleForm" class="easyui-form" data-options="novalidate:true"  method="post" >' +
                        '<div style="float: left" >标题: <input id="title" style="width: 405px"  type="text" name="title" class="easyui-textbox  easyui-validatebox"  data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;" >分类: <input id="nameTop" style="width: 205px"  type="text" name="pid" class="easyui-textbox easyui-validatebox" data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;" >标签：<input id="label" style="width: 205px"  type="text" name="label" class="easyui-textbox easyui-validatebox" data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;">推荐：<input id="recommend" type="text"  name="recommend" class="easyui-combobox" style="width: 205px"'+
                        'data-options="valueField:\'value\',textField:\'text\',editable:false,'+
                        'data:[{text:\'是\',value:1},{text:\'否\',value:0,selected:true}]" /></div>'+
                        '<div style="width: 100%;height: 100%;margin-top: 30px;">' +
                        '<textarea id="myArea" style="width: 100%;height: 100%;"></textarea></div></form>';
                    $("#datetabs").tabs('add',{
                        title:title,
                        content:content,
                        closable:true
                    });
                    addArea("myArea");//初始化富文本框
                //=============================弹出框的树结构============================================//
                    $("#nameTop").combotree({
                        method:'post',
                        url: blogArticle.URL.listCategoryTree,
                        parentField:"pid",
                        textFiled:"name",
                        editable:true,
                        lines:true
                    });
                }
            });
            $("#modifyContent").click(function (){
                blogArticle.isAddOrUpdate = 1;
                var row = $("#listArticleTable").datagrid("getSelected");
                if(!row){
                    $.messager.alert("提示","请选中一行操作!");
                    return;
                }
                var title = "修改"+$("#contentTypeZh").val();
                if ($("#datetabs").tabs('exists', title)){
                    $("#datetabs").tabs('select', title);
                }else {
                    var content =
                        '<form id="modifyArticleForm" class="easyui-form" data-options="novalidate:true"  method="post" >' +
                        '<div style="float: left" >标题: <input id="title2" style="width: 405px"  type="text" name="title" class="easyui-textbox  easyui-validatebox"  data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;" >分类: <input id="nameTop2" style="width: 205px"  type="text" name="pid" class="easyui-textbox easyui-validatebox"   data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;" >标签：<input id="label2" style="width: 205px"  type="text" name="label" class="easyui-textbox easyui-validatebox"   data-options="required:true" /></div>' +
                        '<div style="float: left;margin-left: 10px;">推荐：<input id="recommend2" type="text"  name="recommend" class="easyui-combobox" style="width: 205px"'+
                        'data-options="valueField:\'value\',textField:\'text\',editable:false,'+
                        'data:[{text:\'是\',value:1},{text:\'否\',value:0,selected:true}]" /></div>'+
                        '<div style="width: 100%;height: 100%;margin-top: 30px;" >' +
                        '<textarea id="myArea2" style="width: 100%;height: 100%;"></textarea></div></form>';
                    $("#datetabs").tabs('add',{
                        title:title,
                        content:content,
                        closable:true
                    });
                    addArea("myArea2");//初始化富文本框
                    }
                //默认值赋予
                //=============================弹出框的树结构============================================//
                $("#nameTop2").combotree({
                    method:'post',
                    url: blogArticle.URL.listCategoryTree,
                    parentField:"pid",
                    textFiled:"name",
                    editable:true,
                    lines:true
                });
                $("#title2").textbox("setValue",row.title);
                $("#nameTop2").combotree("setValue",row.categoryId);
                $("#label2").textbox("setValue", row.label);
                $("#label2").textbox("setText",row.label);
                //根据索引获取处于第一位置的tab 进行赋值
                var tabtitle = $('.tabs-selected').text();                                      //获取选中tab的title
                var tabindex = $('#datetabs').tabs("getTabIndex",$('#datetabs').tabs('getSelected'));//获取选中tab的index
                if (tabindex == 1 && tabtitle == "修改" + $("#contentTypeZh").val()) {
                    $($(".nicEdit-main")[0]).html(row.content);
                }else if (tabindex == 2 && tabtitle == "修改" + $("#contentTypeZh").val()) {
                    $($(".nicEdit-main")[1]).html(row.content);
                }
            });
            //***********************删除
            $("#deleteContent").click(function (){


                var row = $("#listArticleTable").datagrid("getSelections")
                var ids = new Array();
                if(row.length>0){
                    $.messager.confirm("提示","确定删除选中文章?",function (e){
                        if(e){
                            $.each(row,function (index,data){
                                ids.push(data.id);
                            })
                            $.post(blogArticle.URL.deleteArticle,{ids:ids},function (data){
                                if(data.type == "success"){
                                    $("#listArticleTable").datagrid('options').queryParams = "";
                                    blogArticle.tableObj.datagrid("reload");
                                    blogArticle.ajaxCache = [];
                                }
                            })
                        }
                    })
                }else{
                    $.messager.alert("提示","请先选中一行！")
                }
            });

        //******************保存触发事件
            $("#saveContent").click(function (){

                //根据索引 保存富文本框值
                var newContentValue = "";
                var modifyContentValue = "";
                var title = $('.tabs-selected').text();
                var index = $('#datetabs').tabs("getTabIndex",$('#datetabs').tabs('getSelected'));

                if(index == 1 && title == "新建"+$("#contentTypeZh").val()){
                    newContentValue = $($(".nicEdit-main")[0]).html();
                    modifyContentValue = $($(".nicEdit-main")[1]).html();
                }else if(index == 1 && title == "修改"+$("#contentTypeZh").val()){
                    modifyContentValue = $($(".nicEdit-main")[0]).html();
                    newContentValue = $($(".nicEdit-main")[1]).html();
                }
                $.messager.confirm("提示","确定提交？",function (e){
                    if(e){
                        //新增保存
                        if(blogArticle.isAddOrUpdate == 0){
                            $("#addArticleForm").form("submit",{
                                url:blogArticle.URL.addArticle,
                                onSubmit:function(param){
                                    param.contentType = $("#contentTypeZh").val();
                                    param.content = newContentValue;
                                    return $(this).form('enableValidation').form('validate');
                                },
                                success:function(dataobj){
                                    dataobj = eval("("+dataobj+")")
                                    if(dataobj.type == 'success'){
                                        $("#datetabs").tabs("close","新建"+$("#contentTypeZh").val());
                                        $("#listArticleTable").datagrid('options').queryParams = "";  //清空查询条件
                                        $("#saveContent").hide();//隐藏按钮
                                        blogArticle.tableObj.datagrid("reload");
                                        blogArticle.ajaxCache[blogArticle.inputValue]=[];
                                    }else if(dataobj.type == 'error'){
                                        $.messager.alert("提示",dataobj.text);
                                    }else {
                                        $.messager.alert("提示","未知错误");
                                    }
                                }
                            })
                        }else if(blogArticle.isAddOrUpdate == 1){                   //修改保存
                            var row = $("#listArticleTable").datagrid("getSelections");
                            var rows = $(row[0])[0];     //JQ对象化

                            $("#modifyArticleForm").form("submit",{
                                url:blogArticle.URL.updateArticle,
                                onSubmit:function(param){
                                    param.id = rows.id;
                                    param.content = modifyContentValue;
                                    param.contentType = $("#contentTypeZh").val();
                                    return $(this).form('enableValidation').form('validate');
                                },
                                success:function(dataobj){
                                    dataobj = eval("("+dataobj+")")
                                    if(dataobj.type == 'success'){
                                        $("#datetabs").tabs("close","修改"+$("#contentTypeZh").val());
                                        $("#listArticleTable").datagrid('options').queryParams = "";  //清空查询条件
                                        $("#saveContent").hide();//隐藏按钮
                                        blogArticle.tableObj.datagrid("reload");
                                        blogArticle.ajaxCache[blogArticle.inputValue]=[];
                                    }else if(dataobj.type == 'error'){
                                        $.messager.alert("提示",dataobj.text);
                                    }else {
                                        $.messager.alert("提示","未知错误");
                                        $('#addRoleDialog').dialog('close');
                                    }
                                }
                            })
                        }
                    }
                })
            });

        //控制按钮之间的显示顺序和逻辑
        $('#datetabs').tabs({
            onSelect:function(title,index){
                if(title=="新建"+$("#contentTypeZh").val()){
                    blogArticle.isAddOrUpdate = 0;
                    $("#newContent").hide();
                    $("#saveContent").show();
                    $("#deleteContent").hide();
                    $("#modifyContent").hide();
                }else if(title=="修改"+$("#contentTypeZh").val()){
                    blogArticle.isAddOrUpdate = 1;
                    $("#modifyContent").hide();
                    $("#saveContent").show();
                    $("#deleteContent").hide();
                    $("#newContent").hide();
                }else if(title == $("#contentTypeZh").val()+"列表"){
                    blogArticle.isAddOrUpdate = 0;
                    $("#modifyContent").show();
                    $("#newContent").show();
                    $("#deleteContent").show();
                    $("#saveContent").hide();
                };
            }
        });
    }

    function getCont(value){
        var start_ptn = /(<.[^>]+>)*/gmi;		//过滤标签开头
        var end_ptn = /<\/?\w+>$/;			//过滤标签结束
        var space_ptn = /(&nbsp;)*/;			//过滤空格
        var c1 = value.replace(start_ptn,"").replace(end_ptn).replace(space_ptn,"");
        return c1;
    }
    //搜索
    this.initSearch = function (){
        $("#searchDivChioce").hide();

        $("#searchContent").blur(function (){
            setTimeout(clear,200);
        })

        $("#searchBtn").click(function (){
            var content = $("#searchContent").val();
            if(content.length==0||content==""){
                $("#listArticleTable").datagrid('options').queryParams = "";  //清空查询条件
                $("#listArticleTable").datagrid('reload');
            }else{
                $("#listArticleTable").datagrid('options').queryParams = "";  //清空查询条件
                $("#listArticleTable").datagrid('reload');
            }
        })

        function clear(){
            $("#searchDivChioce").html(" ")
            $("#searchDivChioce").hide()
        }

        var timeout = 0;

        $('#searchContent').keyup(function(){
            blogArticle.inputValue = $(this).val();
            clearTimeout(timeout);
            timeout = setTimeout(function(){
                if(!!blogArticle.ajaxCache[blogArticle.inputValue]){
                    $("#searchDivChioce").show();
                    var data = blogArticle.ajaxCache[blogArticle.inputValue]
                    var str = ' <ul class="searchList">';
                    $.each(data, function (index,data){//<a href="#" ref="'+data.title+'" rel="'+data.type+'" rev="'+data.id+'" >'+data.title+'</a>
                        str = str + '<li ><div class="searchListlia" ref="'+data.title+'" rel="'+data.type+'" rev="'+data.id+'" >'+data.title+'</div><span>'+data.type+'</span></li>'
                    })
                    str = str + '</ul>'
                    $("#searchDivChioce").html(str);
                    $('.searchListlia').click(function(){
                        $("#searchContent").val($(this).attr("ref"))
                        var svalue = {id:$(this).attr("rev"),title:$(this).attr("ref"),type:$(this).attr("rel")}
                        getMoreInfo(svalue)
                    });
                }else{
                    $.ajax({
                        url:blogArticle.URL.searchContent,
                        method:'post',
                        data:{strValue:$('#searchContent').val(),contentType:$("#contentTypeZh").val()},
                        success:function(data){
                            $("#searchDivChioce").show();
                            var str = ' <ul class="searchList">';
                            $.each(data, function (index,data){//<a  href="#" ref="'+data.title+'" rel="'+data.type+'" rev="'+data.id+'">'+data.title+'</a><span>'+data.type+'</span>
                                str = str + '<li class="searchListli" ref="'+data.title+'" rel="'+data.type+'" rev="'+data.id+'"><div class="searchListlia" >'+data.title+'</div><span>'+data.type+'</span></li>'
                            })
                            str = str + '</ul>'
                            $("#searchDivChioce").html(str);
                            //显示自动提示框，给框里填关联词条的内容
                            blogArticle.ajaxCache[blogArticle.inputValue]=[];
                            blogArticle.ajaxCache[blogArticle.inputValue]=data;//给缓存对象赋值

                            $("#searchDivChioce").html(str);
                            $('.searchListli').click(function(){
                                $("#searchContent").val($(this).attr("ref"))
                                var svalue = {id:$(this).attr("rev"),title:$(this).attr("ref"),type:$(this).attr("rel")}
                                getMoreInfo(svalue)
                            });
                        }
                    });
                }
            },200);
        });

        function getMoreInfo(value){
            $("#listArticleTable").datagrid('options').queryParams = value;
            $("#listArticleTable").datagrid('options').dataType="json";
            //$("#listArticleTable").datagrid('options').url=blogArticle.URL.list;
            $("#listArticleTable").datagrid('reload');
        }
    }


    this.init = function(){
        blogArticle.dataGridInit();     //列表显示初始化
        blogArticle.buttonInit();       //按钮显示初始化
        blogArticle.initSearch();         //搜索功能初始化
    }
}

$(function(){
    new blogArticle().init();
})